package com.ferrlo.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.image.ImageCaptchaService;

public class ImageCaptchaServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ImageCaptchaService service = SampleImageCaptchaService.getInstance();
		// set content type as jpeg
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		// create the image using session ID
		// logger.fine("tring to get image captcha service");
		BufferedImage bufferedImage = service.getImageChallengeForID(request
				.getSession(true).getId());
		ServletOutputStream servletOutputStream = response.getOutputStream();

		// write the image to the servlet output stream
		// logger.fine("tring to output buffered image to servlet output stream");
		ImageIO.write(bufferedImage, "jpg", servletOutputStream);
		

		try {
			servletOutputStream.flush();
		} finally {
			servletOutputStream.close();
		}

	}
}
